package vip.manda.framework.web.http;

import cn.hutool.core.util.ReflectUtil;
import vip.manda.framework.util.Triad;
import vip.manda.framework.log.Log;
import vip.manda.framework.log.LogFactory;
import vip.manda.framework.web.WebFunction;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author hongda.li 2022-04-11 16:48
 */
public class Interceptor implements Filter {
    private static final Log log = LogFactory.getLog();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("Interceptor start working");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        boolean doFilter = true;
        for (Triad<Class<?>, Object, Method> filter : WebFunction.getFilters()) {
            log.info("Filter intervene[{}]", filter.getX().getName());
            boolean result = ReflectUtil.invoke(filter.getY(), filter.getZ(), request, response);
            if (!result){
                doFilter = false;
                break;
            }
        }
        if (doFilter){
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
